package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.NavDao;
import com.cn.wanxi.dao.impl.NavImpl;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.service.INavService;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

public class NavServiceImpl implements INavService {
    @Override
    public List<NavModel> getNavList() {
        NavDao navDao = new NavImpl();
        List<NavModel> list = new ArrayList<>();
        Jedis jedis = new Jedis();
        long length = jedis.llen("navId");
        if (length > 0) {
//取得缓存里面的数据，并封装到list里面
            List<String> ids = jedis.lrange("navId", 0, length);
            List<String> hrefs = jedis.lrange("href", 0, length);
            List<String> titles = jedis.lrange("title", 0, length);
            for (int i = 0; i < length; i++) {
                NavModel navModel = new NavModel();
                navModel.setId(Integer.parseInt(ids.get(i)));
                navModel.setTitle(titles.get(i));
                navModel.setHref(hrefs.get(i));
                list.add(navModel);
            }
            System.out.println("缓存");
        } else {
            list = navDao.getNavList();
            for (int i = 0; i < list.size(); i++) {
                jedis.rpush("navId", list.get(i).getId().toString());
                jedis.rpush("href", list.get(i).getHref());
                jedis.rpush("title", list.get(i).getTitle());
//                jedis.expire("id", 3000000);
            }
            System.out.println("数据库");
        }
        return list;
    }
}
